import { type Reactive, reactive } from "vue";
import { get as _get, set as _set } from "lodash-es";

export function useReactive<T extends object>(initState: T) {
  const state = reactive(initState);

  const initialStateCopy: T = { ...initState };

  // 获取当前状态
  const get = <K extends keyof Reactive<T>>(key: K): Reactive<T>[K] =>
    state[key];

  // 设置状态的某个属性
  const set = <K extends keyof Reactive<T>>(
    key: K,
    value: Reactive<T>[K]
  ): void => {
    state[key] = value;
  };

  // 更新状态
  const update = (patch: Partial<T>): void => {
    Object.keys(patch).forEach((key) => {
      if (key in state) {
        _set(state, key, _get(patch, key));
      }
    });
  };

  // 重置状态到初始值
  const reset = (initState?: T): void => {
    Object.assign(state, initState ? initState : initialStateCopy);
  };

  return [
    state,
    {
      get,
      set,
      update,
      reset,
    },
  ] as const;
}
